<template>
  <jy-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
    <el-upload multiple :action="uploadFileUrl" :data="uploadData" :before-upload="handleBeforeUpload"
      :file-list="fileList" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"
      :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" class="upload-file-uploader"
      ref="fileUpload">
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b class="red">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b class="red">{{ fileType.join("/") }}</b> </template>
        的文件
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in ossList">
        <el-link @click="download(file)" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.originalName) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-button size="mini" type="text" icon="el-icon-view" @click="previewFile(file)">预览</el-button>
          <el-button size="mini" type="text" class="red cd-mr8" icon="el-icon-delete"
            @click="handleDelete(file)">删除</el-button>
          <!-- <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link> -->
        </div>
      </li>
    </transition-group>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">关 闭</el-button>
    </div>
  </jy-dialog>
</template>
<script>
import { getToken } from "@/utils/auth";
import { listOss, delOss } from "@/api/system/oss";
import { filePreview } from '@/utils/fileUtils';
export default {
  name: 'FileUploadView',
  props: {
    moduleKey: {
      type: String,
      default: ""
    },
    isReadonly: {
      type: Boolean,
      default () {
        return false;
      }
    },
    // 数量限制
    limit: {
      type: Number,
      default: 10,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "docx", "xlsx", "xls", "pdf", "png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      loading: false,
      title: "附件上传",
      open: false,
      businessId: null,
      ossList: [],
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/oss/uploadBusinessFile", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadData: {
        businessId: this.businessId,
        moduleKey: this.moduleKey,
        sort: 0,
      },
      fileList: [],
    };
  },
  created () {
  },
  mounted () {
  },
  methods: {
    init (id) {
      this.ossList = [];
      this.businessId = id;
      this.uploadData.businessId = id;
      this.getList();
      this.open = true;
    },
    getList () {
      this.loading = true;
      const queryParams = {
        pageNum: 1,
        pageSize: 100,
        moduleKey: this.moduleKey,
        businessId: this.businessId
      };
      listOss(queryParams).then((response) => {
        this.ossList = response.rows;
        this.loading = false;
      });
    },
    cancel () {
      this.ossList = [];
      this.open = false;
    },
    // 上传前校检格式和大小
    handleBeforeUpload (file) {
      if (this.limit <= this.ossList.length) {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
        return false;
      };
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // 校验文件列表内是否包含该文件名称
      if (this.ossList.length > 0) {
        let arr = []; //
        this.ossList.forEach(item => {
          arr.push(item.originalName);
        });
        if (arr.includes(file.originalName)) {
          this.$modal.msgError(`您上传的文件名称在当前列表已存在!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed () {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError (err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess (res, file) {
      this.getList();
      this.$modal.closeLoading();
    },
    // 删除文件
    handleDelete (row) {
      const ossIds = row.ossId;
      this.$modal
        .confirm('是否确认删除"' + row.originalName + '"?')
        .then(() => {
          this.loading = true;
          return delOss(ossIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 预览文件
    async previewFile (file) {
      const arr = [".pdf", ".png", ".jpg", ".jpeg"];
      if (arr.includes(file.fileSuffix)) {
        // window.open(file.url);
        window.open(this.fileUrlTransition(file.url));

        return;
      }
      const path = file.url; //要预览文件的访问地址
      const url = filePreview(path);
      window.open(url);

      // 使用js预览
      // let response = await fetch(file.fileUrl)
      // let blob = await response.blob()
      // const info = { url: file.fileUrl, blob: blob, filename: file.name }
      // this.$refs.filePreviewRef.init(info)
    },

    // 上传结束处理
    uploadedSuccessfully () {
    },
    // 获取文件名称
    getFileName (name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString (list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].ossId + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
    // 文件地址转换
    fileUrlTransition (url) {
      if (process.env.VUE_APP_FILE_PATH != undefined) {
        // 截取路径前半部分
        const path = process.env.VUE_APP_OSS_PATH;
        if (url.lastIndexOf(path) > -1) {
          return location.origin + process.env.VUE_APP_FILE_PATH + url.slice(url.lastIndexOf(path) + path.length);
        }
      }
      return url;
    },
    // 下载
    async download (row) {
      this.$download.oss(row.ossId);
    },
  },
};
</script>
<style lang="scss" scoped>
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action {
  width: 100px;
  display: flex;
  align-items: center;
}

.red {
  color: #f56c6c
}
</style>
